package cn.ljl.org.service.impl;

import cn.ljl.basic.service.impl.BaseServiceImpl;
import cn.ljl.org.domain.Department;
import cn.ljl.org.mapper.DepartmentMapper;
import cn.ljl.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 业务实现类：部门
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> deptTree() {
        List<Department> departments = departmentMapper.loadAll();
        //1.将所有部门信息保存在map中，方便根据id去获取部门信息，就不用查数据库了
        Map<Long,Department> map = new HashMap<>();
        for (Department department : departments) {
            map.put(department.getId(),department);
        }

        List<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            if(department.getParent_id()==null){//顶级部门
                //2.遍历所有的部门，如果是顶级部门[parent_id==null],加到部门树
                deptTree.add(department);
            }else{
                //3.如果不是顶级部门[parent_id!=null],找到自己的父部门，将自己加到父部门的children
                //获取父部门的id - 获取父部门对象 - 获取父部门的children集合
                Long parentId = department.getParent_id();
                //根据id获取父部门
                Department parentDepartment = map.get(parentId);
                //防止父部门的数据删除引起的空指针异常
                if(parentDepartment!=null){
                    parentDepartment.getChildren().add(department);
                }
            }
        }
        return deptTree;
    }
}
